package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.common.ApUserThreadLocalUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Autowired
    ApUserSearchService apUserSearchService;

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if(dto.getSearchWords()==null){
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", dto.getSearchWords()));
        }
        ApUser apUser = ApUserThreadLocalUtil.getThreadLocal();
        //异步调用保存搜索记录
        apUserSearchService.insert(dto.getSearchWords(),apUser.getId());

        if (dto.getMinBehotTime()!=null){
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lte(dto.getMinBehotTime()));
        }
        searchRequest.source().query(boolQueryBuilder);
        searchRequest.source().from(dto.getPageNum()*dto.getPageSize()).size(dto.getPageSize());

        HighlightBuilder highlight=new HighlightBuilder();
        highlight.field("title");
        highlight.requireFieldMatch(false);
        highlight.preTags("<font style='color: red; font-size: inherit;'>");
        highlight.postTags("</font>");
        searchRequest.source().highlighter(highlight);
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        return result(response);
    }



    /**
     * 抽取的封装结果的方法
     * @param response
     * @return
     */
    private ResponseResult result(SearchResponse response) {

        List<Map> list=new ArrayList<>();

        //获取命中的结果
        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            //获取查询结果，返回是map集合
            Map<String, Object> map = hit.getSourceAsMap();
            //高亮数据封装
            //如果高亮域中有值
            if(hit.getHighlightFields().size()>0){
                //取出高亮域
                Text[] titles = hit.getHighlightFields().get("title").fragments();
                if(titles.length>0){
                    //把高亮之后的h_tile=<font>测试</font>
                    map.put("h_title",titles[0].toString());
                }
            }else{
                //表示没有高亮域，我们则把h_title=测试
                map.put("h_title",map.get("title"));
            }
            //把获取的结果封装到list
            list.add(map);
        }
        return  ResponseResult.okResult(list);
    }




}


